#!/bin/sh
# Copyright (c) 2015 Oracle and/or its affiliates. All Rights Reserved.
# Copyright (c) International Business Machines  Corp., 2005
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it would be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Author: Mitsuru Chinen <mitch@jp.ibm.com>

TST_TOTAL=2
TCID=if-route-adddel

. if-lib.sh

TST_CLEANUP="do_cleanup"

CHECK_INTERVAL=${CHECK_INTERVAL:-$(($NS_TIMES / 20))}

do_cleanup()
{
	cleanup
	restore_ipaddr
}

test_body()
{
	local cmd_type=$1

	case $cmd_type in
	rt_cmd) local cmd_name='route' ;;
	ip_cmd) local cmd_name='ip' ;;
	*) tst_brkm TBROK "Unknown test parameter '$cmd_type'"
	esac

	local iface=$(tst_iface)
	local inet="inet$TST_IPV6"
	local new_rt=
	local opt_rt=
	if [ "$TST_IPV6" ]; then
		new_rt=${IPV6_NET32_UNUSED}::
		opt_rt="/64"
	else
		new_rt="${IPV4_NET16_UNUSED}.23.0"
		case $cmd_type in
		rt_cmd) ;;
		ip_cmd) opt_rt='/24' ;;
		esac
	fi

	tst_resm TINFO "'$cmd_name' add/del ${new_rt}${opt_rt} $NS_TIMES times"

	if ! restore_ipaddr; then
		tst_resm TBROK "Failed to set default IP addresses"
		return
	fi

	make_background_tcp_traffic

	local cnt=1
	while [ $cnt -le $NS_TIMES ]; do
		case $cmd_type in
		rt_cmd) route -A $inet add ${new_rt}${opt_rt} dev $iface ;;
		ip_cmd) ip route add ${new_rt}${opt_rt} dev $iface ;;
		esac
		if [ $? -ne 0 ]; then
			tst_resm TFAIL "Can't add route $new_rt to $iface"
			return
		fi

		case $cmd_type in
		rt_cmd) route -A $inet del ${new_rt}${opt_rt} dev $iface ;;
		ip_cmd) ip route del ${new_rt}${opt_rt} dev $iface ;;
		esac
		if [ $? -ne 0 ]; then
			tst_resm TFAIL "Can't del route $new_rt from $iface"
			return
		fi

		check_connectivity $cnt || return

		# Check the background TCP traffic
		pgrep -x netstress > /dev/null || make_background_tcp_traffic

		cnt=$(($cnt + 1))
	done

	tst_resm TPASS "Test is finished correctly"
}

setup

tst_check_cmds route

test_body 'rt_cmd'
test_body 'ip_cmd'

tst_exit
